package com.cxmx.escort.common.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * 当把Person类作为BeanUtilTest的内部类时，程序出错<br>
 * java.lang.NoSuchMethodException: Property '**' has no setter method<br>
 * 本质：内部类 和 单独文件中的类的区别 <br>
 * BeanUtils.populate方法的限制：<br>
 * The class must be public, and provide a public constructor that accepts no
 * arguments. <br>
 * This allows tools and applications to dynamically create new instances of
 * your bean, <br>
 * without necessarily knowing what Java class name will be used ahead of time
 */
public class BeanUtils {
    private static List<String> notGetListProperties = new ArrayList<String>();

    static {
        notGetListProperties.add("serialVersionUID");
        notGetListProperties.add("nowPage");
        notGetListProperties.add("rowCount");
        notGetListProperties.add("pageSize");
        notGetListProperties.add("pageCount");
        notGetListProperties.add("pageOffset");
        notGetListProperties.add("pageTail");
        notGetListProperties.add("orderField");
        notGetListProperties.add("orderDirection");
        notGetListProperties.add("length");
        notGetListProperties.add("startIndex");
        notGetListProperties.add("endIndex");
        notGetListProperties.add("indexs");
        notGetListProperties.add("list");
        notGetListProperties.add("list2");
        notGetListProperties.add("id");
    }

    /**
     * @param object
     * @return false : 对象为null,或者【map】【list】【set】为空时,true：对象不为null ,或者【map】【list】【set】 不为空
     */
    public static boolean isNullOrEmpty(Object object) {
        boolean resultFlag = false;
        if (null == object) {
            resultFlag = true;
        } else if ("".equals(object)) {
            resultFlag = true;
        } else {
            resultFlag = false;
            if (object instanceof Map) {
                resultFlag = ((Map) object).isEmpty();
            }
            if (object instanceof List) {
                resultFlag = ((List) object).isEmpty();
            }
            if (object instanceof Set) {
                resultFlag = ((Set) object).isEmpty();
            }
        }
        return resultFlag;
    }

    /**
     * @param object
     * @return true : 对象不为null,并且【map】【list】【set】不为空时,flse：对象为null ,或者【map】【list】【set】 为空
     */
    public static boolean isNotNullOrEmpty(Object object) {
        return !isNullOrEmpty(object);
    }


    // Map --> Bean 2: 利用org.apache.commons.beanutils 工具类实现 Map --> Bean

    /**
     * 【mongo map 慎用,不支持  对象里面包含自定义对象的转换】
     *
     * @param map
     * @param obj
     */
    public static void transMap2Bean2(Map<String, Object> map, Object obj) {
        if (map == null || obj == null) {
            return;
        }
        try {
            org.apache.commons.beanutils.BeanUtils.populate(obj, map);
        } catch (Exception e) {
            System.out.println("transMap2Bean2 Error " + e);
        }
    }

    // Map --> Bean 1: 利用Introspector,PropertyDescriptor实现 Map --> Bean
    @Deprecated
    public static void transMap2Bean(Map<String, Object> map, Object obj) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo
                    .getPropertyDescriptors();

            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();

                if (map.containsKey(key)) {
                    try {
                        Object value = map.get(key);
                        // 得到property对应的setter方法
                        Method setter = property.getWriteMethod();
                        setter.invoke(obj, value);

                    } catch (Exception e) {
                        System.out.println("transMap2Bean Error " + e);
                        continue;
                    }

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("transMap2Bean Error " + e);
        }

        return;

    }

    /**
     * Map转成实体对象
     *
     * @param map map实体对象包含属性
     * @param
     * @return
     */
    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null) {
            return null;
        }
        Object obj = beanClass.newInstance();

        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }

            field.setAccessible(true);
            field.set(obj, map.get(field.getName()));
        }

        return obj;


    }

    // Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map
    public static Map<String, Object> transBean2Map(Object obj) {

        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo
                    .getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();

                // 过滤class属性
                if (!("class").equals(key)) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                    map.put(key, value);
                }

            }
        } catch (Exception e) {
            System.out.println("transBean2Map Error " + e);
        }

        return map;

    }

    public static Map<String, Object> transBean2MapNotEmpty(Object obj) {
        Map<String, Object> saveMap = new HashMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 过滤非数据表字段
                if (!key.equals("class")
                        && !key.equals("tableName")
                        && !key.equals("serialVersionUID")
                        && !key.equals("queryFields")) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                    if (value != null) {
                        saveMap.put(key, value);
                    }
                }
            }

        } catch (Exception e) {
            System.out.println("transBean2Map Error " + e);
        }
        return saveMap;
    }

    public static boolean isChinese(String strName) {
        char[] ch = strName.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    // 根据Unicode编码完美的判断中文汉字和符号
    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }

    /**
     * 将一个对象转换为另一个对象
     *
     * @param <T1>      要转换的对象
     * @param <T2>      转换后的类
     * @param orimodel  要转换的对象
     * @param castClass 转换后的类
     * @return 转换后的对象
     */
    public static <T1, T2> T2 convertBean(T1 orimodel, Class<T2> castClass) {
        T2 returnModel = null;
        try {
            returnModel = castClass.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("创建" + castClass.getName() + "对象失败");
        }
        List<Field> fieldlist = new ArrayList<Field>(); //要转换的字段集合
        while (castClass != null && //循环获取要转换的字段,包括父类的字段
                !castClass.getName().toLowerCase().equals("java.lang.object")) {
            fieldlist.addAll(Arrays.asList(castClass.getDeclaredFields()));
            castClass = (Class<T2>) castClass.getSuperclass(); //得到父类,然后赋给自己
        }
        for (Field field : fieldlist) {
            PropertyDescriptor getpd = null;
            PropertyDescriptor setpd = null;
            try {
                getpd = new PropertyDescriptor(field.getName(), orimodel.getClass());
                setpd = new PropertyDescriptor(field.getName(), returnModel.getClass());
            } catch (Exception e) {
                continue;
            }
            try {
                Method getMethod = getpd.getReadMethod();
                Object transValue = getMethod.invoke(orimodel);
                Method setMethod = setpd.getWriteMethod();
                setMethod.invoke(returnModel, transValue);
            } catch (Exception e) {
                throw new RuntimeException("cast " + orimodel.getClass().getName() + "to "
                        + castClass.getName() + " failed");
            }
        }
        return returnModel;
    }

//    public static void main(String args[]) {
//          System.out.println((int)(Math.random()*9000)+1000);
////        List arrList = new ArrayList();
////        System.out.println(isNullOrEmpty(arrList));
////        String str = "海口港";
////        System.out.println(str.endsWith("港") == true ? str.substring(0, str.length() - 1) : str);
//
//
//    }

}


